<?php

namespace app\pay\controller;

use think\facade\Config;
use think\facade\Db;
use AopSDK\AopClient;
use AopSDK\request\AlipayTradePayRequest;
use AopSDK\request\AlipayOpenAuthTokenAppRequest;

class Alipay
{
    public function test()
    {
        $sfz = file_get_contents('./sfz1.jpg');
        echo urlencode(base64_encode($sfz));
    }

    public function index()
    {

        return view();
    }

    /**
     * 当面付收款
     */
    public function codepay()
    {
        $subject = input('subject', '服务费', 'trim');
        $code = input('code', '', 'trim');
        $money = input('money', 0, 'floatval');

        // 商户资料
        $mch_id = '2088502994920532';
        $mch_token = '202011BB6778d8987fde445ba96b9d91b54c5C53';

        $aop = new AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = Config::get('alipay.appId');
        $aop->rsaPrivateKey = Config::get('alipay.privateKey');
        $aop->alipayrsaPublicKey = Config::get('alipay.publicKey');
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';

        $item = [
            'out_trade_no' => uniqid(),
            'auth_code' => $code,
            'subject' => $subject,
            'total_amount' => $money,
            'scene' => 'bar_code',
            'query_options' => ['fund_bill_list', 'voucher_detail_list', 'discount_goods_detail'],
            'seller_id' => $mch_id
        ];
        $request = new AlipayTradePayRequest();
        $request->setBizContent(json_encode($item));
        $result = $aop->execute($request, "", $mch_token);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {          //交易成功
            $result = json_decode(json_encode($result), true)['alipay_trade_pay_response'];

            $result['status'] = 1;
            print_r($result);
        } else if (!empty($resultCode) && $resultCode == 10003) {   //需要用户输入支付密码
            echo '需要输入密码';
        } else {//交易失败
            echo $result->$responseNode->sub_msg;
        }
    }

    public function auth_success()
    {
        $source = input('source', '', 'trim');
        $app_id = input('app_id', '', 'trim');
        $shop_id = input('state', 0, 'intval');
        $app_auth_code = input('app_auth_code', '', 'trim');

        $shop = Db::name('shop')
            ->where('id', $shop_id)
            ->find();
        if ($source == 'alipay_app_auth' && $app_id && $shop) {
            $server = Db::name('server')
                ->where([
                    ['type', '=', 'alipay'],
                    ['config', 'like', '%{"appid":"' . $app_id . '"%']
                ])
                ->find();
            $serverConfig = @json_decode($server['config'], true);
            $aop = get_alipay_aop($serverConfig);

            $request = new AlipayOpenAuthTokenAppRequest ();
            $request->setBizContent(json_encode([
                'grant_type' => 'authorization_code',
                'code' => $app_auth_code
            ]));
            $result = $aop->execute($request);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                $now = time();
                $token = $result->$responseNode->tokens[0];
                $user_id = $token->user_id;
                $app_auth_token = $token->app_auth_token;
                $app_refresh_token = $token->app_refresh_token;
                $expires_in = $now + intval($token->expires_in);
                $re_expires_in = $now + intval($token->re_expires_in);

                $jinjian = Db::name('jinjian_alipay')
                    ->where('shop_id', $shop_id)
                    ->find();
                if ($jinjian) {
                    Db::name('jinjian_alipay')
                        ->where('shop_id', $shop_id)
                        ->update([
                            'server_id' => $server['id'],
                            'batch_status' => 'submit',
                            'order_status' => 'MERCHANT_CONFIRM_SUCCESS',
                            'merchant_pid' => $user_id,
                            'app_auth_token' => $app_auth_token,
                            'app_refresh_token' => $app_refresh_token,
                            'expires_in' => $expires_in,
                            're_expires_in' => $re_expires_in,
                            'update_time' => $now
                        ]);
                } else {
                    Db::name('jinjian_alipay')
                        ->where('shop_id', $shop_id)
                        ->insert([
                            'agent_id' => $shop['agent_id'],
                            'shop_id' => $shop_id,
                            'server_id' => $server['id'],
                            'batch_status' => 'submit',
                            'order_status' => 'MERCHANT_CONFIRM_SUCCESS',
                            'merchant_pid' => $user_id,
                            'app_auth_token' => $app_auth_token,
                            'app_refresh_token' => $app_refresh_token,
                            'expires_in' => $expires_in,
                            're_expires_in' => $re_expires_in,
                            'update_time' => $now,
                            'add_time' => $now
                        ]);
                }

                // 配置商家支付宝支付参数
                Db::name('shop')
                    ->where('id', $shop_id)
                    ->update([
                        'alipay_config' => json_encode([
                            'alipay_status' => 1,
                            'alipay_type' => 'server',
                            'alipay_server_id' => $server['id'],
                            'alipay_pid' => $user_id,
                            'alipay_token' => $app_auth_token,
                            'alipay_rate' => $jinjian['activities_rate'] ? $jinjian['activities_rate'] : 0.38
                        ])
                    ]);
            }
        }

        return view('auth_success');
    }

    public function message_notify()
    {
        // file_put_contents('./message.txt', date('Y-m-d H:i:s') . "\n", 8);
        // file_put_contents('./message.txt', json_encode($_POST) . "\n\n", 8);
        $notify_type = input('post.notify_type', '', 'trim');
        if ($notify_type != 'open_app_auth_notify') {
            exit();
        }
        $app_id = input('post.app_id', '', 'trim');
        $server = Db::name('server')
            ->where([
                ['type', '=', 'alipay'],
                ['config', 'like', '{"appid":"' . $app_id . '"%']
            ])
            ->find();
        if (!$server) {
            exit();
        }
        $biz_content = input('post.biz_content', '', 'trim');
        $sign = input('post.sign', '', 'trim');
        $sign_type = input('post.sign_type', 'RSA2', 'trim');
        if (empty($biz_content) || empty($sign)) {
            exit();
        }
        // 验签
        $serverConfig = @json_decode($server['config'], true);
        $aop = get_alipay_aop($serverConfig);
        $checkSign = $aop->rsaCheckV1($_POST, null, $sign_type);
        if (!$checkSign) {
            die('checkSign Fail');
        }

        $biz_content = json_decode($biz_content);
        $batch_no = $biz_content->notify_context->trigger_context->out_biz_no;
        $jinjian = Db::name('jinjian_alipay')
            ->where('batch_no', $batch_no)
            ->find();
        if (!$jinjian) {
            exit();
        }
        // 更新进件记录里的token
        $detail = $biz_content->detail;
        $now = time();
        Db::name('jinjian_alipay')
            ->where('id', $jinjian['id'])
            ->update([
                'batch_status' => 'submit',
                'order_status' => 'MERCHANT_CONFIRM_SUCCESS',
                'merchant_pid' => $detail->user_id,
                'app_auth_token' => $detail->app_auth_token,
                'expires_in' => $now + $detail->expires_in,
                'app_refresh_token' => $detail->app_refresh_token,
                're_expires_in' => $now + $detail->expires_in,
                'update_time' => $now
            ]);

        // 配置商家支付宝支付参数
        Db::name('shop')
            ->where('id', $jinjian['shop_id'])
            ->update([
                'alipay_config' => json_encode([
                    'alipay_status' => 1,
                    'alipay_type' => 'server',
                    'alipay_server_id' => $server['id'],
                    'alipay_pid' => $detail->user_id,
                    'alipay_token' => $detail->app_auth_token,
                    'alipay_rate' => $jinjian['activities_rate'] ? $jinjian['activities_rate'] : 0.38
                ])
            ]);
        die('success');
    }

    public function voucher_notify()
    {

    }
}
